import datetime

from django.shortcuts import render
from django.utils import timezone

from userInformation.models import *
from django.shortcuts import HttpResponse
from flight.models import *
from flight.views import *
import json
import django.utils.timezone


# Create your views here.
def home(request):
    username = ''
    if request.session.get('username'):
        username = request.session['username']
    message = 'welcome'
    data = {
        'username': username,
        'message': message,
    }
    return HttpResponse(json.dumps(data))


def register(request):
    if request.method == 'POST':
        req = json.loads(request.body)
        new_userid = req['username']
        new_password = req['password']
        is_admin = req['is_admin']
        user = UserInfo.objects.filter(userId=new_userid)
        if user:
            data = {
                'success': 0,
            }
            return HttpResponse(json.dumps(data))
        new_user = UserInfo()
        new_user.userId = new_userid
        new_user.password = new_password
        new_user.isAdmin = is_admin
        new_user.save()
        new_credit = Credit()
        new_credit.userId = new_userid
        new_credit.creditLevel = 1
        new_credit.save()
        data = {
            'success': 1,
        }
        return HttpResponse(json.dumps(data))
    else:
        data = {}
        return HttpResponse(json.dumps(data))


def login(request):
    if request.method == 'POST':
        req = json.loads(request.body)
        userId = req['username']
        password = req['password']
        users = UserInfo.objects.filter(userId=userId)
        if not users:
            data = {
                'success': 0,
            }
            return HttpResponse(json.dumps(data))
        user = users[0]
        if password == user.password:
            request.session['userId'] = userId
            request.session['isAdmin'] = user.isAdmin
            data = {
                'userID': userId,
                'success': 1,
            }
            return HttpResponse(json.dumps(data))
        data = {
            'success': 0,
        }
        return HttpResponse(json.dumps(data))
    else:
        data = {}
        return HttpResponse(json.dumps(data))


def checkCredit(userId):
    user = Credit.objects.get(userId=userId)
    return user.creditLevel


def lowerCredit(userId):
    now = timezone.now()
    now = str(now).split('.')[0]
    now = datetime.strptime(now, "%Y-%m-%d %H:%M:%S")
    user = Credit.objects.get(userId=userId)
    records = RefondRecord.objects.filter(userId=userId)
    recent_records = []
    for record in records:
        if not DateCompare(record.date, now, 30, 0, 0,
                           0):
            recent_records.append(record)

    if len(recent_records) == 0:
        user.creditLevel = 1
        user.save()
    if len(recent_records) == 2:
        user.creditLevel = 2
        user.save()
    if len(recent_records) >= 3 and user.creditLevel == 2:
        user.creditLevel = 0
        user.save()
        return False
    return True


def bookticket(request):
    if request.method == "POST":
        req = json.loads(request.body)
        name = req['flightName']
        startTime = req['startTime']
        flights = FlightInfo.objects.filter(flightName=name, startTime=startTime)
        if not flights:
            data = {
                'success': 0,
            }
            return HttpResponse(json.dumps(data))
        flight = flights[0]
        if checkCredit(req['userId']) == 0:
            data = {
                'success': 0,
            }
            return HttpResponse(json.dumps(data))
        if flight.leftSeat > 0:
            new_ticket = TicketInfo()
            new_ticket.userId = req['userId']
            if checkCredit(req['userId']) == 0:
                data = {
                    'success': 0,
                }
                return HttpResponse(json.dumps(data))
            else:
                new_ticket.flightId = flight.id
                new_ticket.flightName = req['flightName']
                new_ticket.price = req['price']
                new_ticket.passengername = req['passengerName']
                new_ticket.passengerId = req['passengerId']
                new_ticket.flightId = req['flightId']
                new_ticket.save()
                flight.leftSeat = flight.leftSeat - 1
                flight.save()
                data = {
                    'success': 1,
                }
                return HttpResponse(json.dumps(data))
        else:
            data = {
                'success': -1,
            }
            return HttpResponse(json.dumps(data))
    else:
        data = {
            'success': 0,
        }
        return HttpResponse(json.dumps(data))


def check_in(request):
    if request.method == "POST":
        req = json.loads(request.body)
        ticket = TicketInfo.objects.get(id=req['ticketId'])
        if ticket.seatNo is None:
            data = {
                'success': 0,
            }
            return HttpResponse(json.dumps(data))
        if ticket:
            ticket.seatNo = req['seatNo']

            flight = FlightInfo.objects.get(id=ticket.flightId)
            if flight.state != 2:
                data = {
                    'success': -1,
                }
                return HttpResponse(json.dumps(data))
            seatnum = int(ticket.seatNo)
            s1 = list(flight.seatInfo)
            s1[seatnum] = '0'
            flight.seatInfo = "".join(s1)

            flight.save()
            ticket.save()
            data = {
                'success': 1,
            }
            return HttpResponse(json.dumps(data))
        else:
            return HttpResponse(json.dumps({'success': 0, }))


def listtickets(request):
    if request.method == "POST":
        req = json.loads(request.body)
        userId = req['userId']
        tickets = TicketInfo.objects.filter(userId=userId)
        data = {'root': []}
        count = 0
        for ticket in tickets:
            no = []
            ticketInfo = {}
            ticketInfo['ticketId'] = ticket.id
            ticketInfo['flightName'] = ticket.flightName
            ticketInfo['passengerId'] = ticket.passengerId
            ticketInfo['price'] = str(ticket.price)
            ticketInfo['flightId'] = ticket.flightId
            ticketInfo['seatNo'] = ticket.seatNo
            flights = FlightInfo.objects.filter(id=ticket.flightId)
            if len(flights) == 0:
                data = {
                    'success': 0,
                }
                return HttpResponse(json.dumps(data))
            flight = flights[0]
            ticketInfo['startTime'] = str(flight.startTime)
            ticketInfo['endTime'] = str(flight.endTime)
            ticketInfo['startPos'] = flight.startPos
            ticketInfo['endPos'] = flight.endPos
            ticketInfo['state'] = flight.state
            no.append(ticketInfo)
            count += 1
            data['root'].append(no)
        return HttpResponse(json.dumps(data))


def printTicket(request):
    if request.method == "POST":
        req = json.loads(request.body)
        ticket = TicketInfo.objects.get(flightName=req['flightName'], passengerId=req['passengerId'])
        if ticket:
            flight = FlightInfo.objects.get(flightName=req['flightName'])
            data = {
                'id': ticket.id,
                'flightName': ticket.flightName,
                'seatNo': ticket.seatNo,
                'startPos': flight.startPos,
                'endPos': flight.endPos,
                'startTime': str(flight.startTime),
                'endTime': str(flight.endTime),
                'startAir': flight.startAir,
                'endAir': flight.endAir,
                'flightStatus': flight.state,
                'pricce': str(ticket.price),
                'passengerName': ticket.passengerName,
                'success': 1,
            }
            return HttpResponse(json.dumps(data))
        else:
            data = {
                'success': 0,
            }
            return HttpResponse(json.dumps(data))
    else:
        data = {
            'success': 0,
        }
        return HttpResponse(json.dumps(data))


def endorse(request):
    if request.method == "POST":
        req = json.loads(request.body)
        old_ticket = TicketInfo.objects.get(id=req['oldId'])
        if old_ticket:
            old_flight = FlightInfo.objects.get(id=req['oldflightId'])
            old_flight.leftSeat = old_flight.leftSeat + 1
            old_flight.save()
            new_flight = FlightInfo.objects.get(id=req['newflightId'])
            if new_flight:
                if new_flight.leftSeat > 0:
                    new_flight.leftSeat = new_flight.leftSeat - 1
                    new_ticket = TicketInfo()
                    new_ticket.userId = old_ticket.userId
                    new_ticket.flightName = new_flight.flightName
                    new_ticket.flightId = new_flight.id
                    new_ticket.price = str(new_flight.price)
                    new_ticket.passengerId = old_ticket.passengerId
                    new_ticket.save()
                    old_ticket.passengerId = '0'
                    old_ticket.userId = '0'
                    old_ticket.save()
                    new_flight.save()
                    data = {
                        'succcess': 1,
                    }
                    return HttpResponse(json.dumps(data))
                else:
                    data = {
                        'success': 0,
                    }
                    return HttpResponse(json.dumps(data))
            else:
                return HttpResponse(json.dumps({}))
    else:
        data = {
            'success': 0,
        }
        return HttpResponse(json.dumps(data))


def refund(request):
    if request.method == "POST":
        req = json.loads(request.body)
        old_ticket = TicketInfo.objects.get(id=req['ticketId'])
        userId = req['userId']
        record = RefondRecord()
        record.userId = userId
        dateTime = str(timezone.now())
        dateTime = dateTime.split(".")[0]
        a = datetime.strptime(dateTime, "%Y-%m-%d %H:%M:%S")
        record.date = a
        record.ticketId = old_ticket.id
        record.save()
        lowerCredit(userId)
        if old_ticket:
            old_ticket.passengerId = '0'
            old_ticket.userId = '0'
            old_ticket.save()
            old_flight = FlightInfo.objects.get(id=old_ticket.flightId)
            old_flight.leftSeat += 1
            old_flight.save()
            data = {
                'success': 1,
            }
            return HttpResponse(json.dumps(data))
        else:
            data = {
                'success': 0,
            }
            return HttpResponse(json.dumps(data))
    else:
        data = {
            'success': 0,
        }
        return HttpResponse(json.dumps(data))


def delay(request):
    if request.method == "POST":
        req = json.loads(request.body)
        flightname = req['flightName']
        new_date = req['newdate']
        old_date = req['olddate']
        if FlightInfo.objects.filter(fligheName=flightname, startTime=old_date):
            oldflight = FlightInfo.objects.get(flightname=flightname, startTime=old_date)
            delt = oldflight.startTime - oldflight.endTime
            oldflight.isDelay = True
            oldflight.startTime = new_date
            oldflight.endTime = new_date + delt
            oldflight.save()
            data = {
                'success': 1,
            }
            return HttpResponse(json.dumps(data))
        else:
            data = {
                'success': 0,
            }
            return HttpResponse(json.dumps(data))
    else:
        data = {
            'success': 0,
        }
        return HttpResponse(json.dumps(data))


def getState(request):
    if request.method == "POST":
        req = json.loads(request.body)
        id = req['flightId']
        flight = FlightInfo.objects.get(id=id)
        data = {
            'state': flight.state,
        }
        return HttpResponse(json.dumps(data))


def getCity(request):
    if request.method == "GET":
        flights = FlightInfo.objects.all()
        data = {'root': []}
        count = 0
        no = []
        for flight in flights:
            city1 = flight.startPos
            if no.count(city1) == 0:
                no.append(city1)
            city2 = flight.endPos
            if no.count(city2) == 0:
                no.append(city2)
        data['root'].append(no)
        return HttpResponse(json.dumps(data))
